package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.RoleJurisdictionJdbc;
import com.wuseguang.springcloud.service.RoleJurisdictionServic;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.MyDES;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Map;


/**
 * <p>
 * 角色权限 服务实现类
 * </p>
 *
 * @author zmc
 * @since 2019-11-28
 */
@Service
public class RoleJurisdictionServicImpl implements RoleJurisdictionServic {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RoleJurisdictionJdbc jurisdictionJdbc;

    /**
     * @描述 家长端查应用模块
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result queryFunctionFindAll(Integer schoolId) {
        String sql = " SELECT j.id,j.name,j.image icon,j.p_router router FROM school_jurisdiction s,jurisdiction j  WHERE s.jurisdiction_id=j.id AND s.school_id=? AND j.papplet=1 GROUP BY j.id";
        return new Result(jurisdictionJdbc.queryListMap(sql, schoolId));
    }

    /**
     * @描述 教师端查个人信息
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result queryTeacherInformationById(Integer id) {
        String sql = "SELECT name,head_portrait,IF(sex=0,'男','女') sex,diploma,DATE_FORMAT(entry_time,'%Y-%m-%d') entry_time,phone,password  FROM teacher WHERE id=?";
        Map<String, Object> map = jurisdictionJdbc.queryMap(sql, id);
        map.put("password", MyDES.decryptBasedDes(map.get("password").toString()));
        return new Result(map);
    }

    /**
     * @描述 教师端修改密码
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result updateTeacherChangePasswordById(Integer id, String password) {
        String sql = "UPDATE teacher set   password =?  WHERE id=?";
        int i = jurisdictionJdbc.updateByParameter(sql, MyDES.encryptBasedDes(password), id);
        if (i > 0) {
            return new Result();
        }
        return new Result(CodeUtil.ADD_FAILURE);
    }

    /**
     * @描述 修改头像
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result updateTeacherHeadPortrait(Integer id, String HeadPortrait) {
        String sql = "UPDATE teacher set   head_portrait =?  WHERE id=?";
        int i = jurisdictionJdbc.updateByParameter(sql, HeadPortrait, id);
        if (i > 0) {
            return new Result();
        }
        return new Result(CodeUtil.ADD_FAILURE);
    }


    /**
     * @描述 家长端查个人信息
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result queryParentInformationById(Integer id) {
        String sql = "SELECT s.head_portrait,s.student_name,c.name cname,IF(s.sex=0,'男','女') sex,s.card_number stu_no,s.phone,s.bancard_password,p.password,p.nickname,p.headimgurl  FROM parent p LEFT JOIN parent_student t ON p.id=t.parent_id  LEFT JOIN student s ON t.student_id=s.id LEFT JOIN classes c ON s.class_id=c.id WHERE s.id=?";
        Map<String, Object> map = jurisdictionJdbc.queryMap(sql, id);
        map.put("password", decryptBasedDes(map.get("password") != null ? map.get("password").toString() : null));
        map.put("bancard_password", decryptBasedDes(map.get("bancard_password") != null ? map.get("bancard_password").toString() : null));
        return new Result(map);
    }


    public String decryptBasedDes(String cryptData) {
        byte[] DES_KEY = {21, 1, -110, 82, -32, -85, -128, -65};
        String decryptedData = null;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            // 把字符串解码为字节数组，并解密
            decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
        } catch (Exception e) {
            // log.error("解密错误，错误信息：", e);

        }
        return decryptedData;
    }


    /**
     * @描述 家长端修改小程序密码或班牌密码
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result updateParentChangePasswordById(Integer id, String password, int type) {
        String sql = "";
        //修改小程序密码
        if (type == 0) {
            sql = "UPDATE parent set   password =?  WHERE id=(SELECT t.parent_id FROM parent_student t WHERE t.student_id=? )";
        } else {//修改班牌个人中心密码
            sql = "UPDATE student set   bancard_password =?  WHERE id=?";
        }
        int i = jurisdictionJdbc.updateByParameter(sql, MyDES.encryptBasedDes(password), id);
        if (i > 0) {
            return new Result();
        }
        return new Result(CodeUtil.ADD_FAILURE);
    }

    /**
     * @描述 修改头像
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result updateStudentHeadPortrait(Integer id, String HeadPortrait) {
        String sql = "UPDATE student set   head_portrait =?  WHERE id=?";
        int i = jurisdictionJdbc.updateByParameter(sql, HeadPortrait, id);
        if (i > 0) {
            return new Result();
        }
        return new Result(CodeUtil.ADD_FAILURE);
    }
}
